package cn.rkylin.oms.accountreport.adapter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlipayUserAccountreportGetRequest;
import com.taobao.api.response.AlipayUserAccountreportGetResponse;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.accountreport.domain.taobao.TopAccountreport;

/**
 * 
 * 淘宝账单代理
 * 
 * @author jipengcheng
 * @created 2017.04.25
 */
@Service("taoBaoAccountreportVisitor")
public class TaoBaoAccountreportVisitor extends AccountreportVisitor {

	private final Log logger = LogFactory.getLog(TaoBaoAccountreportVisitor.class);
	private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	// 数据库访问对象
	@Autowired
	private IDataBaseFactory dao;
	// 每页行数
	private static final Long pageSize = 20L;

	/**
	 * 构造函数
	 */
	public TaoBaoAccountreportVisitor() {

	}

	/**
	 * 获取账单
	 *
	 * @return 0失败, 1成功
	 */
	@Override
	public int getAccountreport(String shopId, Map<String, Object> paramMap) throws Exception {
		try {
			if (shopVO == null) {
				return 0;
			}
			// 按照修改时间 startTime和endTime获取
			if (paramMap.containsKey("startTime") && paramMap.containsKey("endTime")) {
				Calendar startTime = Calendar.getInstance();
				startTime.setTime(simpleDateFormat.parse(paramMap.get("startTime").toString()));
				Calendar endTime = Calendar.getInstance();
				endTime.setTime(simpleDateFormat.parse(paramMap.get("endTime").toString()));
				int r = getAccountreport(startTime, endTime);
				return r;
			}
		} catch (Exception ex) {
			// TODO: handle exception
			logger.error(ex.getMessage(), ex);
		}
		return 0;
	}

	/**
	 * 获取账单
	 *
	 * @return 0失败, 1成功
	 */
	private int getAccountreport(Calendar startModified, Calendar endModified) throws Exception {

		// alipay.user.accountreport.get
		TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
		AlipayUserAccountreportGetRequest req = new AlipayUserAccountreportGetRequest();
		req.setFields("alipay_order_no");
		req.setStartTime(startModified.getTime());
		req.setEndTime(endModified.getTime());
		req.setPageNo(1L);
		req.setPageSize(1L);
		AlipayUserAccountreportGetResponse rsp = client.execute(req, shopVO.getSessionKey());
		if (rsp.isSuccess() == false) {

			if (StringUtils.isNotEmpty(rsp.getSubMsg())) {
				// 如果返回 "查询总数超限,请调整查询条件"
				if (rsp.getSubMsg().contains("查询总数超限,请调整查询条件")) {

					// 按照每10分钟递增轮询获取
					Calendar endCalendar = Calendar.getInstance();
					endCalendar.setTime(startModified.getTime());
					endCalendar.add(Calendar.MINUTE, 10);
					// 时间比较
					while (endCalendar.getTimeInMillis() < endModified.getTimeInMillis()) {
						// 获取数据
						if (getAccountreport(startModified, endCalendar) == 0) {
							return 0;
						}

						// 更新时间
						startModified.setTime(endCalendar.getTime());
						endCalendar.add(Calendar.MINUTE, 10);
					}
					// 最后获取一遍
					return getAccountreport(startModified, endCalendar);
				}

				if (rsp.getSubMsg().contains("时间跨度必须只有一天")) {
					// 按照每天递增轮询获取
					Calendar endCalendar = Calendar.getInstance();
					endCalendar.setTime(startModified.getTime());
					endCalendar.add(Calendar.DATE, 1);
					// 时间比较
					while (endCalendar.getTimeInMillis() < endModified.getTimeInMillis()) {
						// 获取数据
						if (getAccountreport(startModified, endCalendar) == 0) {
							return 0;
						}

						// 更新时间
						startModified.setTime(endCalendar.getTime());
						endCalendar.add(Calendar.DATE, 1);
					}
					// 最后获取一遍
					return getAccountreport(startModified, endCalendar);
				}
			}
			return 0;
		}

		if (rsp.getAlipayRecords() == null || rsp.getAlipayRecords().size() < 1) {
			return 1;
		}

		long totalPageNo = rsp.getTotalResults() % pageSize > 0 ? rsp.getTotalResults() / pageSize + 1
				: rsp.getTotalResults() / pageSize;

		if (totalPageNo >= 1) {
			for (long pageNo = totalPageNo; pageNo >= 1; pageNo--) {
				getInventoryItem(startModified, endModified, pageNo);
			}
		}
		return 1;
	}

	/**
	 * 获取账单
	 *
	 * @return 0失败, 1成功
	 */

	private int getInventoryItem(Calendar startModified, Calendar endModified, long pageNo) throws Exception {

		// alipay.user.accountreport.get
		TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
		AlipayUserAccountreportGetRequest req = new AlipayUserAccountreportGetRequest();
		req.setFields(
				"create_time,type,business_type,balance,in_amount,out_amount,alipay_order_no,merchant_order_no,self_user_id,opt_user_id,memo");
		req.setStartTime(startModified.getTime());
		req.setEndTime(endModified.getTime());
		req.setPageNo(pageNo);
		req.setPageSize(pageSize);
		AlipayUserAccountreportGetResponse rsp = client.execute(req, shopVO.getSessionKey());
		if (!rsp.isSuccess()) {
			return 0;
		}

		if (rsp.getAlipayRecords() == null || rsp.getAlipayRecords().size() < 1) {
			return 1;
		}

		for (com.taobao.api.domain.AlipayRecord alipayRecord : rsp.getAlipayRecords()) {

			// 获取账单数据
			TopAccountreport topAccountreport = new TopAccountreport();
			String[] excludeArr = { "create_time" };
			BeanUtils.copyProperties(alipayRecord, topAccountreport, excludeArr);
			// 空字段数据处理
			if (StringUtils.isEmpty(alipayRecord.getInAmount())) {
				alipayRecord.setInAmount("0");
			}
			if (StringUtils.isEmpty(alipayRecord.getOutAmount())) {
				alipayRecord.setOutAmount("0");
			}
			if (StringUtils.isEmpty(alipayRecord.getBalance())) {
				alipayRecord.setBalance("0");
			}
			if(StringUtils.isEmpty(alipayRecord.getOptUserId())){
				alipayRecord.setOptUserId("");
			}
			if(StringUtils.isEmpty(alipayRecord.getMemo())){
				alipayRecord.setMemo("");
			}	
			// 数据类型转换
			topAccountreport.setInAmount(BigDecimal.valueOf(new Double(alipayRecord.getInAmount())));
			topAccountreport.setOutAmount(BigDecimal.valueOf(new Double(alipayRecord.getOutAmount())));
			topAccountreport.setBalance(BigDecimal.valueOf(new Double(alipayRecord.getBalance())));

			// 检查账单是否存在
			int tempItem = 0;
			TopAccountreport topAccountreportModel = (TopAccountreport) dao
					.find("selectByAlipayOrderNoTopAccountreport", alipayRecord.getAlipayOrderNo());
			if (topAccountreportModel == null) {
				// 添加TopAccountreport数据
				topAccountreport.setTopAccountReportId(SnoGerUtil.getUUID());
				topAccountreport.setPrjId(shopVO.getPrjId());
				topAccountreport.setPrjName(shopVO.getPrjName());
				topAccountreport.setShopId(shopVO.getShopId());
				topAccountreport.setShopName(shopVO.getShopName());
				topAccountreport.setShopAccount(shopVO.getShopAccount());
				topAccountreport.setShopType(shopVO.getShopType());
				topAccountreport.setCreated(simpleDateFormat.parse(alipayRecord.getCreateTime()));
				topAccountreport.setCreateTime(null);

				tempItem = dao.insert("insertSelectiveTopAccountreport", topAccountreport);
			} else {
				// 更新TopItem数据
				topAccountreport.setTopAccountReportId(topAccountreportModel.getTopAccountReportId());
				tempItem = dao.update("updateByPrimaryKeySelectiveTopAccountreport", topAccountreport);
			}
		}
		return 1;
	}
}
